package com.cbh.binlog.core;

import com.cbh.binlog.common.SpringUtil;
import com.cbh.binlog.config.BinlogClientConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;

/**
 * @author ChenBiHui
 * @date 2025/2/19
 */
public final class DataSourceSchema {

    private volatile HikariDataSource dataSource;

    public DataSource dataSource() throws ClassNotFoundException {
        if (dataSource == null) {
            synchronized (this) {
                if (dataSource == null) {
                    BinlogClientConfig config = SpringUtil.getBean(BinlogClientConfig.class);
                    Class.forName(config.getType());
                    final String url = "jdbc:mysql://" + config.getHost() + ":" + config.getPort() + "/" + config.getSchema() +
                            "?useUnicode=true&" +
                            "characterEncoding=utf8&" +
                            "useSSL=false&" +
                            "serverTimezone=Asia/Shanghai&" +
                            "nullCatalogMeansCurrent=true&" +
                            "allowPublicKeyRetrieval=true&" +
                            "allowMultiQueries=true&" +
                            "autoReconnect=true&" +
                            "rewriteBatchedStatements=true";
                    dataSource = new HikariDataSource();
                    dataSource.setDriverClassName(config.getType());
                    dataSource.setJdbcUrl(url);
                    dataSource.setUsername(config.getUsername());
                    dataSource.setPassword(config.getPassword());
                    dataSource.setMinimumIdle(0);
                    dataSource.setMaximumPoolSize(1);
                    dataSource.setConnectionTimeout(30000);
                    dataSource.setMaxLifetime(500000);
                    dataSource.setKeepaliveTime(60000);
                    dataSource.setPoolName("Monitor-DataSource");
                }
            }
        }
        return dataSource;
    }
}
